/*
 * @Author: qingyuanyang
 * @Date: 2023-09-19 11:05:18
 * @LastEditors: qingyuanyang 1131083582@qq.com
 * @LastEditTime: 2023-10-12 14:22:08
 * @FilePath: /utilization/src/pages/DeviceStatus/index.tsx
 * @Description: 设备状态页面
 */
import { Spin } from 'antd';
import style from './deviceStatus.module.scss';
import Card from '@/components/Card';
import { useState } from 'react';
import { deviceColumns, tabItem } from './type';
import ChangeChart from './components/change-chart';
import {
  DeviceTimeAbnormal,
  getDeviceStatusStatistics,
} from '@/api/deviceStatus';
import { useRequest } from 'ahooks';
import StatusHeader from './components/header';
import Table from '@/components/table';

const DeviceStatus: React.FC = () => {
  const [downData, setDownData] = useState<DeviceTimeAbnormal[]>([]);
  const [offlineData, setOfflineData] = useState<DeviceTimeAbnormal[]>([]);

  const shutDownColumn = deviceColumns.concat([
    {
      title: '关机时长(h)',
      dataIndex: 'duration',
      key: 'duration',
    },
  ]);
  const offlineColumn = deviceColumns.concat([
    {
      title: '离线时长(h)',
      dataIndex: 'duration',
      key: 'duration',
    },
  ]);

  const { loading: statusLoading } = useRequest(
    () => getDeviceStatusStatistics(),
    {
      onSuccess: ({ data }) => {
        tabItem[0].num = data.deviceCount || 0;
        tabItem[1].num = data.deviceTypeCount || 0;
        tabItem[2].num = data.deptCount || 0;
        tabItem[3].num = data.deviceMonthlyIncr || 0;
        tabItem[3].percent = data.deviceMonthlyIncrScale;
        data?.deviceOfflineStatistics?.forEach(item => {
          item.duration = Number(((item.duration as number) / 3600).toFixed(1));
        });
        data?.deviceShutDownStatistics?.forEach(item => {
          item.duration = Number(((item.duration as number) / 3600).toFixed(1));
        });
        setDownData(data?.deviceShutDownStatistics || []);
        setOfflineData(data?.deviceOfflineStatistics || []);
      },
      onError: err => {
        console.log(err);
      },
    }
  );

  return (
    <Spin spinning={statusLoading}>
      <div className={style.status}>
        <StatusHeader tabItem={tabItem} />
        <div className={style.statusTable}>
          <Card title="设备累计关机时长TOP5" tips="当月数据">
            <Table
              dataSource={downData || []}
              columns={shutDownColumn}
              pagination={false}
            />
          </Card>
          <Card
            title="设备累计离线时长TOP5"
            tips="当月数据；连续5分钟没有数据上传，则认为设备离线">
            <Table
              dataSource={offlineData || []}
              columns={offlineColumn}
              pagination={false}
            />
          </Card>
        </div>
        <div className={style.statusChart}>
          <ChangeChart />
        </div>
      </div>
    </Spin>
  );
};

export default DeviceStatus;
